package com.cloud.phone

import android.annotation.SuppressLint
import android.app.AppOpsManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Process
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContract
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ShellUtils
import com.cloud.phone.adapter.ItemAdapter
import com.cloud.phone.base.BaseActivity
import com.cloud.phone.bean.AppInfo
import com.cloud.phone.bean.ListItemBean
import com.cloud.phone.bean.PermissionRqInfo
import com.cloud.phone.broadcastReceiver.AppInstallReceiver
import com.cloud.phone.broadcastReceiver.CloudKillAppBroadcastReceiver
import com.cloud.phone.constants.Constants
import com.cloud.phone.constants.Constants.isServiceApplication
import com.cloud.phone.http.CloudApi
import com.cloud.phone.manager.UserInfoManager
import com.cloud.phone.service.AccessibilityAutoMainService
import com.cloud.phone.service.CloudService
import com.cloud.phone.service.MyNotifyService
import com.cloud.phone.task.SendMsgUtils
import com.cloud.phone.task.TaskManager
import com.cloud.phone.task.bean.FirstSyncServerData
import com.cloud.phone.task.bean.ProxyInfoBean
import com.cloud.phone.utils.AccessibilityUtil
import com.cloud.phone.utils.AppUtils
import com.cloud.phone.utils.FileUtils
import com.cloud.phone.utils.FingerprintGeneratorUtils
import com.cloud.phone.utils.PermissionUtils
import com.cloud.phone.utils.ProxyUtils
import com.cloud.phone.utils.StatuBarUtils
import com.cloud.phone.utils.SystemPropertyUtils
import com.cloud.phone.view.NoDoubleClickListener
import com.cloud.phone.view.TipsDialog
import com.cloud.phone.view.TsUtils
import com.cloud.phone.viewmodel.MainViewModel
import com.cloud.phone.websocket.WebsocketUtil
import com.zhangke.websocket.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Date


class MainActivity : BaseActivity(), ServiceConnection {
    private var  dateFormat:SimpleDateFormat= SimpleDateFormat("HH:mm:ss")
    private var msgDialog: TipsDialog? = null
    private lateinit var workService: MyNotifyService.MyWorkService
    private val TAG = "CloudPhone"
    private var logStr:StringBuffer=StringBuffer()
    private var phoneId = ""
    private var isWorkingStr = ""
    private var topClickTimes: Int = 0
    private val mAppBroadcastReceiver: CloudKillAppBroadcastReceiver by lazy { CloudKillAppBroadcastReceiver() }
    private var apkName: AppInfo? = null
    private val textView: TextView by lazy { findViewById(R.id.tv_text) }
    private val etFly: EditText by lazy { findViewById(R.id.et_fly) }
    val vpnContent = registerForActivityResult(VpnContent()) {
        if (it) {
            AppUtils.startVpn(this)
        }
    }
    private val mainViewModel: MainViewModel by lazy { MainViewModel() }

    companion object {
        @JvmField
        var isInitActivity = 0//用于标识mainActivity是否已经初始化过
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            MainActivity()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isInitActivity = 1
        window.setFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        )//保持屏幕唤醒
        //去除小米手机白色状态栏
        StatuBarUtils.setStatusBarTranslucent(this, true)
        setContentView(R.layout.activity_main)
        //initBootService()
        getData()
        initView()
        registerKillAppReceiver()
        registerAppInstallReceiver()
        //低内存测试时开放下面代码，目前云手机内存是8G
        //mallocMem(7600)
        autoAccessibility()
        autoBootVpn()
        initPermission()
        //getToken()
        initFirstInstallData()
    }


    //首次安装时同步服务端数据
    private fun initFirstInstallData() {
        WebsocketUtil.getWebsocketUtil().syncFirstInstallData()
    }

    private fun getToken() {
        try {
            if (TextUtils.isEmpty(phoneId)) {
                phoneId = "d40d47e2610240db8f0081f20a1dfd80"
            }
            GlobalScope.launch {
                withContext(Dispatchers.IO){
                    val tokenData = CloudApi.getHttp().getToken(phoneId,"1")
                    LogUtils.d(TAG,"===请求到的数据为==="+GsonUtils.toJson(tokenData))
                }
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    private fun isFlyAgreePrivacy() {
        LogUtils.d(TAG, "===是否同意协议===${UserInfoManager.getIsPrivacy()}")
        etFly.requestFocus()
        etFly.hasFocus()
        if (UserInfoManager.getIsPrivacy()) {
            KeyboardUtils.hideSoftInput(this)
            etFly.clearFocus()
        } else {
            if (etFly.hasFocus()) {
                KeyboardUtils.showSoftInput()
                MainScope().launch {
                    withContext(Dispatchers.IO) {
                        //由于软键盘弹出协议时间所以延时2s
                        delay(2000)
                        val cmd = "input tap 181 1089"
                        val cmd2 = "input tap 147 1137"
                        ShellUtils.execCmd(cmd, true)
                        UserInfoManager.setIsPrivacy(true)
                        KeyboardUtils.hideSoftInput(this@MainActivity)
                    }
                }
            } else {
                KeyboardUtils.hideSoftInput(this)
                etFly.clearFocus()
            }
        }
    }

    private fun initPermission() {
        if (checkPermissions()) {
            //有权限
        } else {
            requestPermission()
        }
    }

    private fun requestPermission() {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        android.Manifest.permission.READ_MEDIA_IMAGES,
                        android.Manifest.permission.READ_MEDIA_AUDIO,
                        android.Manifest.permission.READ_MEDIA_VIDEO
                    ),
                    Constants.REQUEST_CODE_PERMISSIONS
                )
            }

            else -> {
                ActivityCompat.requestPermissions(
                    this,
                    Constants.REQUIRED_PERMISSIONS, Constants.REQUEST_CODE_PERMISSIONS
                )
            }
        }
    }

    private fun checkPermissions(): Boolean {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                val permissions = arrayOf(
                    android.Manifest.permission.READ_MEDIA_IMAGES,
                    android.Manifest.permission.READ_MEDIA_AUDIO,
                    android.Manifest.permission.READ_MEDIA_VIDEO,
                )
                for (permission in permissions) {
                    return Environment.isExternalStorageManager()
                }
            }

            else -> {
                for (permission in Constants.REQUIRED_PERMISSIONS) {
                    if (ContextCompat.checkSelfPermission(
                            this, permission
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        return false
                    }
                }
            }
        }
        return true
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReceiveSetVpnSyncTask(firstSyncServerData: FirstSyncServerData){
        autoBootVpn()
    }


    private fun autoBootVpn() {
        LogUtil.d(TAG, "===代理地址为===" + ProxyUtils.getSocksUrl())
        val socksArray = ProxyUtils.getSocksUrl()
        if (!Constants.IS_MY_VPN_SERVICE_RUNNING) {
            if (!TextUtils.isEmpty(ProxyUtils.getSocksUrl())) {
                AppUtils.prepareVpn(this)
            }
        }
        /*else{//保留重启后停止代理发送任务状态给后台
            AppUtils.stopVpn(this@MainActivity)
        }*/
        sendMsgToServer(socksArray)
    }

    private fun sendMsgToServer(socksArray: String?) {
        try {
            val proxyInfoBean = ProxyInfoBean()
            if (socksArray?.isNotEmpty() == true) {
                val socks = socksArray.split(":")
                socks.let {
                    proxyInfoBean.apply {
                        this.account = it[0]
                        this.password = socks[1].split("@")[0]
                        this.ip = socks[1].split("@")[1]
                        this.port = socks[2].toInt()
                        LogUtils.d(TAG, "===代理地址为===" + this.ip)
                        TsUtils.showTips("===代理地址为===${this.ip}")
                    }
                }
            }
            LogUtils.d(TAG, "===设置的vpn状态为3333===" + Constants.IS_MY_VPN_SERVICE_RUNNING)
            Constants.TASK_STATUS = true
            Constants.TASK_IS_RUNNING = true
            proxyInfoBean.id = ProxyUtils.getTaskId()
            LogUtils.d(TAG, "===发送给服务器的信息为===${GsonUtils.toJson(proxyInfoBean)}")
            SendMsgUtils.sendMsgBean(proxyInfoBean)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onVpnOpenMsgReceived(permissionRqInfo: PermissionRqInfo) {
        TsUtils.showTips("权限申请：完成开启VPN")
        AppUtils.prepareVpn(this)
        TsUtils.showTips("VPN开启完成")
    }

    /**
     * 执行此操作就不需要手动去获取token并连接socket了
     */
    private fun autoGetTokenAndStartService() {
        val manager = WebsocketUtil.getWebsocketUtil().mWebSocketManager
        if (manager == null || !manager.isConnect) {
            initWebSocket()
        }
    }

    private fun autoAccessibility() {
        if (isServiceApplication) {
            try {
                //云手机自动获取root权限
                ShellUtils.execCmd(
                    "adb shell cmd activity add-root-permission com.cloud.phone",
                    true
                )
                SystemPropertyUtils.autoAccessService(
                    this@MainActivity,
                    AccessibilityAutoMainService::class.java
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //检测用户是否对本app开启了“Apps with usage access”权限
    private fun hasPermission(): Boolean {
        val appOps = getSystemService(APP_OPS_SERVICE) as AppOpsManager
        var mode = 0
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            mode = appOps.checkOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS,
                Process.myUid(), packageName
            )
        }
        return mode == AppOpsManager.MODE_ALLOWED
    }

    private fun initBootService() {
        val serviceIntent = Intent(this, CloudService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent)
        } else {
            startService(serviceIntent)
        }
    }

    private fun registerKillAppReceiver() {
        try {
            val filter = IntentFilter(Constants.ACTION_APP_KILLED)
            registerReceiver(mAppBroadcastReceiver, filter)
        } catch (exc: Exception) {
            exc.printStackTrace()
        }
    }

    private fun registerAppInstallReceiver() {
        var receiver = AppInstallReceiver()
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_PACKAGE_ADDED)
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED)
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED)
        filter.addDataScheme("package")
        registerReceiver(receiver, filter)
    }

    private fun getData() {
        phoneId = SystemPropertyUtils.getSystemProperty("phone.id").toString()
        LogUtils.d(TAG, "===华为云手机id为===$phoneId")
    }

    private fun getSystemInfo() {
        val systemInfo = SystemPropertyUtils.getSystemProperty("ro.product.manufacturer")
        LogUtils.d(TAG, "===手机制造商为==$systemInfo")
        val fingerprint = SystemPropertyUtils.getSystemProperty("ro.build.fingerprint")
        LogUtils.d(TAG, "===手机系统指纹为==$fingerprint")
        val fingerprint1 = FingerprintGeneratorUtils.generateFingerprint()
        LogUtils.d(TAG, "生成手机系统指纹fingerprint: $fingerprint1")
        val bootImage = SystemPropertyUtils.getSystemProperty("ro.bootimage.build.fingerprint")
        LogUtils.d(TAG, "===手机BootImage系统指纹为==$bootImage")
        var msg = Message.obtain()
        msg.obj =
            "厂商(ro.product.manufacturer)：" + systemInfo.toString() + "\n指纹(ro.build.fingerprint)：" + fingerprint + "\nBootImage指纹(ro.bootimage.build.fingerprint)：" + bootImage
        EventBus.getDefault().post(msg)
    }

    private fun initView() {
        val rlTitle = findViewById<RelativeLayout>(R.id.rl_title)
        val etInput2 = findViewById<EditText>(R.id.et_input2)
        val tvVersion = findViewById<TextView>(R.id.tv_version)

        val packageInfo: PackageInfo = packageManager.getPackageInfo(packageName, 0)
        buildString {
            if (BuildConfig.DEBUG) {
                append("version beta ")
            } else {
                append("version")
            }
            append(packageInfo.versionName)
        }.also { tvVersion.text = it }
        textView.setOnClickListener {
            startUpdateAccountInfo()
        }
        val killAll = findViewById<TextView>(R.id.tv_kill)
        killAll.setOnClickListener {
            getSystemInfo()
            //开始下载apk
            startDownLoadApp()
        }
        val open = findViewById<TextView>(R.id.tv_open)
        open.setOnClickListener {
            //启动任务
            var manager = WebsocketUtil.getWebsocketUtil().mWebSocketManager
            if (manager != null && !manager.isConnect) {
                manager.disConnect()
            }
            if (!isServiceApplication) {
                if (!AccessibilityUtil.isStartAccessibilityServiceEnable(this)) {
                    showOpenAccessibilityTips()
                }
            }
            WebsocketUtil.getWebsocketUtil().initHttpConfig()
        }
        val vpn = findViewById<TextView>(R.id.tv_open_vpn)
        val closeVpn = findViewById<TextView>(R.id.tv_close_vpn)
        //设置主页面的按钮点击事件
        val rcView = findViewById<RecyclerView>(R.id.rc_items)
        val ctTest = findViewById<ConstraintLayout>(R.id.ct_test)
        initItemList(rcView)
        ctTest.visibility = View.GONE
        rcView.visibility = View.VISIBLE

        vpn.setOnClickListener {
            FileUtils.saveFileText(logStr.toString())
            Toast.makeText(this, "已导出日志到根目录CloudLog_ymd.txt", Toast.LENGTH_SHORT).show()
        }

        closeVpn.setOnClickListener {
            val tv_info = findViewById<TextView>(R.id.tv_info)
            logStr= StringBuffer()
            tv_info.text=""
        }

        //顶部标题栏点击5次可切换测试模式或正式模式
        rlTitle.setOnClickListener {
            topClickTimes++
            if (topClickTimes >= 5) {
                if (ctTest.visibility == View.VISIBLE) {
                    ctTest.visibility = View.GONE
                    rcView.visibility = View.VISIBLE
                } else {
                    ctTest.visibility = View.VISIBLE
                    rcView.visibility = View.GONE
                }
                topClickTimes = 0
            }
        }

        val tvSocketInfo = findViewById<TextView>(R.id.tv_socket_info)
        tvSocketInfo.setOnClickListener {
            topClickTimes++
            if (topClickTimes >= 5) {
                if (ctTest.visibility == View.VISIBLE) {
                    ctTest.visibility = View.GONE
                    rcView.visibility = View.VISIBLE
                } else {
                    ctTest.visibility = View.VISIBLE
                    rcView.visibility = View.GONE
                }
                topClickTimes = 0
            }
        }
    }


    fun copyTextToClipboard( text: CharSequence) {
        val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        clipboard.setPrimaryClip(ClipData.newPlainText("label", text))
    }



    private fun startDownLoadApp() {
        MainScope().launch {
            withContext(Dispatchers.IO) {
                //mainViewModel.downLoadApk(Constants.DOWNLOAD_APK_URL, this@MainActivity)
                // MediaScannerHelper.updateToGallery(File(FileManager.TEST_IMAGE_PATH),this@MainActivity)
            }
        }
    }

    //保证应用退到后台而不被杀死
    @SuppressLint("MissingSuperCall")
    override fun onBackPressed() {
        // 当用户按下返回键时，将应用移到后台
        moveTaskToBack(true)
    }

    //执行更新用户信息的任务
    private fun startUpdateAccountInfo() {
        if (WebsocketUtil.getWebsocketUtil().mWebSocketManager != null && !WebsocketUtil.getWebsocketUtil().mWebSocketManager.isConnect) {
            WebsocketUtil.getWebsocketUtil().initHttpConfig()
        }
        if (WebsocketUtil.getWebsocketUtil().msgTaskManger != null) {
//            WebsocketUtil.getWebsocketUtil().msgTaskManger.createUpdatePhoneInfoTask()
            WebsocketUtil.getWebsocketUtil().msgTaskManger.createWhatsAppTask()
        }
//        WebsocketUtil.getWebsocketUtil().msgTaskManger.onHandleMsg(WebsocketUtil.getWebsocketUtil().msgTaskManger.mockData("7"))
//        var rect2= Rect()
//        rect2.left=0
//        rect2.top=0
//        rect2.right=ScreenUtils.getScreenWidth()
//        rect2.bottom=ScreenUtils.getScreenHeight()
//        BingTopDama.takeScreenshotAndSaveToFilePath(rect2,   "测试");
    }

    private fun initItemList(rcView: RecyclerView?) {
        var itemBean = ListItemBean()
        itemBean.setContent("立即同步用户信息至云乐多")
        itemBean.setResImage(R.mipmap.tiktok)
        var list = mutableListOf<ListItemBean>()
        list.add(itemBean)
        var adapter = ItemAdapter(list)
        adapter.onItemClickListener = ItemAdapter.OnItemClickListener {
            if (it == 0) {
                //tiktok
                showTipDialogAndUpdateInfo(it)
            }
        }
        if (rcView != null) {
            var layoutManager = LinearLayoutManager(this)
            layoutManager.orientation = LinearLayoutManager.VERTICAL
            rcView.layoutManager = layoutManager
            rcView.adapter = adapter
        }
    }

    //显示是否需要更新数据的弹框
    private fun showTipDialogAndUpdateInfo(position: Int) {
        var dialog = TipsDialog(this)
        dialog.showMsg(resources.getString(R.string.update_msg_now), View.OnClickListener {
            startUpdateAccountInfo()
            dialog.dismiss()
        })
    }

    private fun initWebSocket() {
        if (!isServiceApplication) {
            if (!Settings.canDrawOverlays(this)) {
                requestOverlayPermission()
                return
            }
        }
        if (!WebsocketUtil.getWebsocketUtil().isInit) {
            WebsocketUtil.getWebsocketUtil().init(this)
        }
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSocketMessageGet(it: Message) {
        val tv_info = findViewById<TextView>(R.id.tv_info)
        val tvSocketInfo = findViewById<TextView>(R.id.tv_socket_info)
        if(logStr.toString().isNotEmpty()){
            if(logStr.startsWith("发送数据失败--->")&&it.obj.toString().contains("发送数据失败--->")){
                return
            }
            if(logStr.length>50000){
                logStr=logStr.delete(25000,50000)
            }
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
            if (it != null) {
                if (it.obj.toString().startsWith("{")) {
                    logStr.insert(0,"\n\n")
                    logStr.insert(0,dateFormat.format(Date())+"-"+"收到消息：" + it.obj.toString())
                    tv_info.text=logStr.toString()
                    return
                }
                if (it.obj.toString().contains("心跳onPong")||it.obj.toString().contains("isWorking=") || it.obj.toString()
                        .contains("socket")
                ) {
                    if(it.obj.toString().contains("isWorking=")) {
                        isWorkingStr = it.obj.toString()
                        var task = TaskManager.getInstance().currentTask
                        if(task!=null){
                            var staus = task.taskStatus
                            var taskType = task.currentTaskType
                            isWorkingStr+=("|taskType=$taskType|status=$staus")
                        }
                        return
                    }
                    tvSocketInfo.text =isWorkingStr+"|"+it.obj.toString()
                } else {
                    if (it.obj.toString().contains("token获取失败")) {
                        logStr.insert(0,"\n\n")
                        logStr.insert(0,dateFormat.format(Date())+"-"+it.obj.toString())
                        tvSocketInfo.text = it.obj.toString()
                        tv_info.text = logStr.toString()
                    } else {
                        logStr.insert(0,"\n\n")
                        logStr.insert(0,it.obj.toString())
                        tv_info.text = logStr.toString()
                    }
                }
            } else {
                LogUtils.i("消息内容==>空")
            }
        } else {
            runOnUiThread(Runnable {
                if (it != null) {
                    if (it.obj.toString().startsWith("{")) {
                        logStr.insert(0,"\n\n")
                        logStr.insert(0,dateFormat.format(Date())+"-"+"收到消息：" + it.obj.toString())
                        tv_info.text=logStr.toString()
                        return@Runnable
                    }
                    if (it.obj.toString().contains("心跳onPong") ||it.obj.toString().contains("isWorking=")|| it.obj.toString()
                            .contains("socket")
                    ) {
                        if(it.obj.toString().contains("isWorking=")) {
                            isWorkingStr = it.obj.toString()
                            var task = TaskManager.getInstance().currentTask
                            if(task!=null){
                                var staus = task.taskStatus
                                var taskType = task.currentTaskType
                                isWorkingStr+=("|taskType=$taskType|status=$staus")
                            }
                            return@Runnable
                        }
                        tvSocketInfo.text =isWorkingStr+"|"+it.obj.toString()
                    } else {
                        if (it.obj.toString().contains("token获取失败")) {
                            logStr.insert(0,"\n\n")
                            logStr.insert(0,dateFormat.format(Date())+"-"+it.obj.toString())
                            tvSocketInfo.text = it.obj.toString()
                            tv_info.text = logStr.toString()
                        } else {
                            logStr.insert(0,"\n\n")
                            logStr.insert(0,dateFormat.format(Date())+"-"+ it.obj.toString())
                            tv_info.text = logStr.toString()
                        }
                    }
                } else {
                    LogUtils.i("消息内容==>空")
                }
            })
        }
    }

    override fun onResume() {
        super.onResume()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        autoGetTokenAndStartService()
        isFlyAgreePrivacy()
//        moveTaskToBack(true)
        LogUtils.d(TAG, "===onResume===")
    }

    override fun onPause() {
        super.onPause()
        LogUtils.d(TAG, "===onPause===")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        isInitActivity = 0//应用被杀了，检测到此处需要重新拉起app
        LogUtils.d(TAG, "===onDestroy===")
        unregisterReceiver(mAppBroadcastReceiver)
    }

    private fun showOpenAccessibilityTips() {
        // 判断服务是否开启
        if (msgDialog != null && msgDialog!!.isShowing) {
            msgDialog!!.dismiss()
            msgDialog = null
        }
        msgDialog = TipsDialog(this)
        msgDialog!!.setCancelable(true)
        msgDialog!!.getHolder().tvSure.text = "去开启"
        msgDialog!!.getHolder().tvcancel.visibility = View.VISIBLE
        msgDialog!!.getHolder().tvContent.text =
            "使用此功能需要开启无障碍服务，请点击去开启手动打开！"
        msgDialog!!.getHolder().tvSure.setOnClickListener(object : NoDoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                msgDialog!!.dismiss()
                PermissionUtils.jumpToSettingPage(this@MainActivity) // 跳转到开启页面
            }
        })
        msgDialog!!.show()
    }


    /**
     * Activity执行结果，回调函数
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // Toast.makeText(activity, "onActivityResult设置权限！", Toast.LENGTH_SHORT).show();
        if (requestCode == Constants.REQUEST_OVERLAY) {
            if (resultCode == RESULT_OK) {
                LogUtils.i("悬浮窗的权限ok了")
            }
        }
        if (requestCode == Constants.REQUEST_PACKAGE_USAGE_STATS) {
            if (resultCode == RESULT_OK) {
                apkName = AppUtils.getRunningProcesses(this)
            } else {
                //ToastUtils.showShort("请开启相应权限")
            }
        }
        if (requestCode == Constants.REQUEST_READ_WRITE_FILE_PERMISSION) {
            if (resultCode == RESULT_OK) {
                TsUtils.showTips("读写文件权限申请成功")
            } else {
                TsUtils.showTips("读写文件权限申请失败")
            }
        }
    }


    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        LogUtils.i("服务已开启")
        //TsUtils.showTips("后台服务已开启")
        workService = service as MyNotifyService.MyWorkService
    }


    override fun onServiceDisconnected(name: ComponentName?) {

    }

    class VpnContent : ActivityResultContract<Intent, Boolean>() {
        override fun createIntent(context: Context, input: Intent): Intent {
            return input
        }

        override fun parseResult(resultCode: Int, intent: Intent?): Boolean {
            return resultCode == RESULT_OK
        }
    }
}